package com.axzhengxin.platform.common.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.axzhengxin.platform.common.exception.ServiceException;
import com.axzhengxin.platform.fspSmsFlowInfo.domain.FspSmsFlowInfo;
import com.axzhengxin.platform.fspSmsFlowInfo.mapper.FspSmsFlowInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.cn;

/**
 * 短信发送服务
 *
 * @Author: syg
 * @Date: 2020/5/8 10:35
 * @Desc: To be or not to be,that is a question.
 */
@Component
public class SmsSendService {

    private static final Logger log = LoggerFactory.getLogger(SmsSendService.class);

    @Autowired
    private IdUtils idUtils;
    /**
     * 腾讯云短信配置信息
     */
    @Value("${config.tencentMsg.url}")
    private String tencentMsgUrl;
    @Value("${config.tencentMsg.appkey}")
    private String tencentMsgAppkey;
    @Value("${config.tencentMsg.sdkappid}")
    private String tencentMsgSdkappid;

    /**
     * 安徽征信内部短信平台配置信息
     */
    @Value("${config.ahjrMsg.url}")
    private String ahjrMsgUrl;
    @Value("${config.ahjrMsg.interfaceNo}")
    private String ahjrMsgInterfaceNo;
    @Value("${config.ahjrMsg.systemCode}")
    private String ahjrMsgSystemCode;
    @Value("${config.ahjrMsg.extendCode}")
    private String ahjrMsgExtendCode;
    @Value("${config.ahjrMsg.messageFormat}")
    private String ahjrMsgMessageFormat;
    @Value("${config.ahjrMsg.sendMethod}")
    private String ahjrMsgSendMethod;
    @Value("${config.ahjrMsg.applicationid}")
    private String ahjrMsgApplicationid;

    @Autowired
    private FspSmsFlowInfoMapper fspSmsFlowInfoMapper;

    /**
     * 生成随验证码
     *
     * @param codeNum
     * @return
     */
    public static String randomCode(int codeNum) {
        int[] codeSource = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        StringBuffer codeBuffer = new StringBuffer();
        for (int i = 0; i < codeNum; i++) {
            codeBuffer.append(codeSource[(int) (Math.random() * 10)]);
        }
        return codeBuffer.toString();
    }

    public String sendMsg(String msgClient, String mobileNo, List<String> paramsList, String content, String templateId) {
        String returnMsg = "";
        try {
            if (("prod").equals(msgClient)) {
                content += "【安徽省中小微企业征信中心服务平台】";
                returnMsg = anHuiMsgChannel(content, mobileNo);
            } else {
                // templateId 为测试环境腾讯云短信平台的模版号
                returnMsg = sendSms(mobileNo, paramsList, templateId, content);
            }
        } catch (Exception ex) {
            throw new ServiceException("网关通信异常", ex);
        }
        if (!returnMsg.equals("")) {
            JSONObject jsonObject = JSONObject.parseObject(returnMsg);
            String returnCode = jsonObject.getString("result");
            String errmsg = jsonObject.getString("errmsg");
            if (returnCode.equals("0")) {
                return "0";
            } else {
//                throw new ServiceException("短信服务"+ errmsg);
                return "-1";
            }
        } else {
//            throw new ServiceException("短信服务未知的错误代码");
            return "-2";
        }
    }

    private String anHuiMsgChannel(String msgConten, String phoneNum) {
        Map<String, String> params = new HashMap<String, String>(32);
        params.put("interfaceNo", ahjrMsgInterfaceNo);
        // 外围系统唯一编码
        params.put("systemCode", ahjrMsgSystemCode);
        // 短信发送至号码
        params.put("destinationAddress", "tel:" + phoneNum);
        // 外围系统唯一的扩展状态码
        params.put("extendCode", ahjrMsgExtendCode);
        // 短信内容文本
        params.put("messageContent", msgConten);
        // 短信息文本类型
        params.put("messageFormat", ahjrMsgMessageFormat);
        // 短信类型
        params.put("sendMethod", ahjrMsgSendMethod);
        params.put("applicationid", ahjrMsgApplicationid);
        String requestJson = JSONObject.toJSONString(params);
        JSONObject obj = new JSONObject();
        try {
            log.info("征信短信平台请求地址 - {} ， 征信短信平台请求参数 -{}", ahjrMsgUrl, requestJson);
            String resultStr = HttpRequest.post(ahjrMsgUrl).header("afemarkId", "aqszxwfsp").contentType("application/json").body(requestJson).timeout(10000).execute().body();
            log.info("征信短信平台返回 - {}", resultStr);
            if (resultStr != null) {
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                if (jsonObject.containsKey("retCode") && jsonObject.containsKey("status") && jsonObject.getString("retCode").equals("000000") && jsonObject.getString("status").equals("0000")) {
                    obj.put("result", "0");
                    obj.put("errmsg", jsonObject.getString("retMsg"));
                } else {
                    obj.put("result", "-1");
                    obj.put("errmsg", jsonObject.getString("retMsg"));
                }
            }
            FspSmsFlowInfo fspSmsFlowInfo = new FspSmsFlowInfo();
            String snakeId = idUtils.getSnakeId();
            long longId = Long.parseLong(snakeId);
            fspSmsFlowInfo.setSfiFlowinfo(snakeId);
            fspSmsFlowInfo.setSpiMsgid(String.valueOf(longId - 1));
            fspSmsFlowInfo.setSpiMobiles(phoneNum);
            fspSmsFlowInfo.setSpiMobilecount("1");
            fspSmsFlowInfo.setSpiContent(msgConten);
            fspSmsFlowInfo.setSpiReturncode("90");
            Date date = new Date();
            String format = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
            fspSmsFlowInfo.setSpiTimestamp(date);
            fspSmsFlowInfo.setSpiSubmittime(format);
            fspSmsFlowInfoMapper.insertFspSmsFlowInfo(fspSmsFlowInfo);

        } catch (Exception e) {
            obj.put("result", "-2");
            obj.put("errmsg", "短信服务异常：" + e);
            log.info("-------------------插入短信记录表------------------");
            FspSmsFlowInfo fspSmsFlowInfo = new FspSmsFlowInfo();
            String snakeId = idUtils.getSnakeId();
            long longId = Long.parseLong(snakeId);
            fspSmsFlowInfo.setSfiFlowinfo(snakeId);
            fspSmsFlowInfo.setSpiMsgid(String.valueOf(longId - 1));
            fspSmsFlowInfo.setSpiMobiles(phoneNum);
            fspSmsFlowInfo.setSpiMobilecount("1");
            fspSmsFlowInfo.setSpiContent(msgConten);
//          throw new ServiceException("短信服务未知的错误代码");
            fspSmsFlowInfo.setSpiReturncode("91");
            Date date = new Date();
            String format = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
            fspSmsFlowInfo.setSpiTimestamp(date);
            fspSmsFlowInfo.setSpiSubmittime(format);
            fspSmsFlowInfoMapper.insertFspSmsFlowInfo(fspSmsFlowInfo);


            throw new ServiceException("征信短信平台返回异常：{} ", e);
//            throw new ServiceException("调用客户短信通道异常");
        }
        return obj.toString();
    }

    public String sendSms(String mobileNo, List<String> paramsList, String templateId, String content)
            throws Exception {
        Random random = new Random();
        long rnd = random.nextInt(999999) % (999999 - 100000 + 1) + 100000;
        String wholeUrl = tencentMsgUrl + "?sdkappid=" + tencentMsgSdkappid + "&random=" + rnd;
        String response = "";
        try {
            JSONObject tel = new JSONObject();
            tel.put("nationcode", "86");
            tel.put("mobile", mobileNo);
            String sig = sha256(String.format(
                    "appkey=%s&random=%s&time=%s&mobile=%s", tencentMsgAppkey, rnd,
                    (System.currentTimeMillis() / 1000), mobileNo));
            JSONObject data = new JSONObject();
            data.put("params", paramsList);
            data.put("sig", sig);
            data.put("tel", tel);
            data.put("time", (System.currentTimeMillis() / 1000));
            // 236998
            data.put("tpl_id", Integer.parseInt(templateId));

            log.info("腾讯云短信请求地址 -{} , 腾讯云短信请求参数 -{}", wholeUrl, data.toString());
            String result = HttpUtil.post(wholeUrl, data.toString());
            log.info("腾讯云短信返回 - {}", result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    private String sha256(String base) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(base.getBytes("UTF-8"));
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
